#include <stdafx.h>
#include <XGuiModule.h>

XGuiModule::XGuiModule()
{

}

void XGuiModule::RegisterWindow(XWindow* window)
{
	window->_register(Texture, Font);
	window->Register();
	Window.push_back(window);
	Drawer->RegisterWindow(window);
}

void XGuiModule::UnregisterWindow(XHash hash)
{
	for(int i=0; i<Window.size(); i++)
	{
		if(Window[i]->Hash == hash)
		{
			Window[i]->Unregister();
			Window.erase(Window.begin() + i);
			Drawer->UnregisterWindow(hash);
			break;
		}
	}
}


void XGuiModule::Initialize(XDrawModule* drawer, XInputModule* input)
{
	Drawer = drawer;
	Input = input;
	Font = new XFont;
	Font->Load("Lucida Grande.ttf", 16);
	Texture = new XTexture;
	Texture->Load("XGui_bg.png");
}

void XGuiModule::PreUpdate()
{
	if(Input->GetMouse().GetLeft().GetCurrent() == true && Input->GetMouse().GetLeft().GetPrevious() == false)
	{
		XPosition pos = Input->GetMouse().GetPosition();

		for(int i=0; i<Window.size(); i++)
		{
			if(pos.X > Window[i]->Rectangle.X && pos.X < Window[i]->Rectangle.X + Window[i]->Rectangle.W && pos.Y > Window[i]->Rectangle.Y && pos.Y < Window[i]->Rectangle.Y + Window[i]->Rectangle.H)
			{
				bool changeActive = true;
				int oldActive = 0;
				for(int j=0; j<Window.size(); j++)
				{
					if(pos.X > Window[j]->Rectangle.X && pos.X < Window[j]->Rectangle.X + Window[j]->Rectangle.W && pos.Y > Window[j]->Rectangle.Y && pos.Y < Window[j]->Rectangle.Y + Window[j]->Rectangle.H)
					{
						if(j != i)
						{
							changeActive = false;
							break;
						}
					}

					if(Window[j]->Hash == ActiveWindow)
						oldActive = j;
				}

				if(changeActive)
				{
					Window[oldActive]->Active = false;
					ActiveWindow = Window[i]->Hash;
					Window[i]->Active = true;

					Drawer->UnregisterWindow(ActiveWindow);
					Drawer->RegisterWindow(Window[i]);
				}
				
			}
		}
	}
	


	for(int i=0; i<Window.size(); i++)
	{
		Window[i]->Update(Input);
	}
}

void XGuiModule::PostUpdate()
{

}

void XGuiModule::Exit()
{
	delete Font;
}